package cn.j0n4than.accountingtool.service.impl;

import cn.j0n4than.accountingtool.entity.User;
import cn.j0n4than.accountingtool.mapper.UserMapper;
import cn.j0n4than.accountingtool.service.UserService;
import cn.j0n4than.accountingtool.utils.BcryptUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 用户服务接口实现
 *
 * @author jonathan
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 更新用户信息
     *
     * @param id   目标用户ID
     * @param user 修改后的User对象
     * @return 影响行数
     */
    @Override
    public Integer update(Integer id, User user) {
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id", id);
        return this.baseMapper.update(user, userUpdateWrapper);
    }

    /**
     * 获取用户分页列表
     *
     * @param page 当前页
     * @param size 页大小
     * @return Page
     */
    @Override
    public Page<User> getPage(Integer page, Integer size) {
        Page<User> userPage = new Page<>(page, size);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //条件...

        return this.baseMapper.selectPage(userPage, userQueryWrapper);
    }

    /**
     * 通过ID获取用户
     *
     * @param id 用户ID
     * @return User
     */
    @Override
    public User getUserById(Integer id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 通过用户名获取用户
     *
     * @param username 用户名
     * @return User
     */
    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);

        return this.baseMapper.selectOne(userQueryWrapper);
    }

    /**
     * 用户登陆功能
     *
     * @param username 用户名
     * @param password 密码
     * @return User
     */
    @Override
    public User login(String username, String password) {
        User user = this.getUserByUsername(username);
        if (user == null) {
            return null;
        }
        if (BcryptUtil.passwordVerify(password, user.password)) {
            //密码验证成功
            return user;
        }
        return null;
    }

    /**
     * 用户注册功能
     *
     * @param username 用户名
     * @param password 密码
     * @param email    电子邮箱
     * @return User
     */
    @Override
    public User reg(String username, String password, String email) {
        User user = new User();
        user.username = username;
        user.password = BcryptUtil.passwordHash(password);
        user.email = email;
        int insert = this.baseMapper.insert(user);
        if (insert > 0) {
            return user;
        }
        return null;
    }
}
